import url from '../data/url'
import URI from 'urijs'
import store from 'store'
import request from '../data/request'

const base = url.base,
  login = request.login,
  getMobileCode = request.getMobileCode,
  bindMobile = request.bindMobile;

const title = '登录'

let form = new Vue({
  el: '#form',
  data: () => ({
    client: 'operate',
    userName: '',
    password: '',
    isLock: false,
    /*    txt: '获取验证码',
     disabled : false*/
  }),
  mounted: function () {
    valid()
  },
  /*  methods: {           //验证码
   prove: () => {
   let t = 60,
   timer;

   timer = setInterval(() => {
   if(t > 0){
   t --;
   form.txt = t+'s';
   form.disabled = true;
   }else {
   form.txt = '重新获取';
   form.disabled = false;
   clearInterval(timer)
   timer = null;
   }
   }, 1000)
   }
   }*/
})

function valid() {

  let form_valid,
      $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true

      $.ajax({
        url: base + login,
        type: 'POST',
        data: {
          client: form.$data.client,
          userName: form.$data.userName,
          password: form.$data.password
        }
      })
        .done(function (res) {
          console.log(res)

          if (res.code === -1) {
            layer.msg(res.message || '未知错误', {
              icon: 5
            })

            form.isLock = false

            return
          }

          if (res.code === 0) {

            /*   if (res.object.securityLeven) {

             bindPhone(res);

             } else {

             if (res.object.data.phone === null) {

             bindPhone(res);

             } else {

             firstLogin(res);

             }
             }*/

            firstLogin(res)
          }
        })
        .fail(function (res) {
          console.log(res)

          layer.msg(`${ title }失败`, {
            icon: 5
          })

          form.isLock = false
        })
        .always(function (res) {

          layer.close(loading_modal)

        })

    }
  })

  // 验证
  form_valid = $form.validate({
    rules: {
      userName: {
        required: true
      },
      passWord: {
        required: true
      }
    }
  })

}

function bindPhone(data) {

  console.log(data.object.data.phone === null)

  let $validPower = $(`<div class="modal fade" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-body">
          <h1 class="text-center">绑定手机号码</h1>
          <h3 class="text-center">为保护帐号安全,请绑定手机号码,验证完后进入首页</h3>
          <form style="margin-top: 40px;">
            <div class="form-group">
              <label>手机号码</label>
              <div class="input-group">
                <input type="text" class="form-control ipt-validPower-mobile" value="${data.object.data.phone ? data.object.data.phone : '' }" ${data.object.securityLeven && data.object.data.phone !== null ? 'disabled' : ''} placeholder="请输入手机号码" autocomplete='off'>
                <span class="input-group-btn">
                  <button class="btn btn-default btn-validPower-getValid" type="button" style='width:100px;'>发送验证码</button>
                </span>
              </div>
            </div>
            <div class="form-group">
              <label>验证码</label>
              <input type="text" class="form-control ipt-validPower-valid" placeholder="请输入验证码" autocomplete='off'>
            </div>
            <button style="margin-top: 30px;" type="button" class="btn btn-block btn-primary btn-validPower-submit" disabled>确认</button>
          </form>
        </div>
      </div>
    </div>
  </div>`);

  let getValidLimit = 60,
    getValidIndex = getValidLimit

  let timer = null

  let mobile = '',
    valid = ''

  let isMobildValid = false

  let $iptMobile = $validPower.find('.ipt-validPower-mobile'),
    $iptValid = $validPower.find('.ipt-validPower-valid'),
    $btnGetValid = $validPower.find('.btn-validPower-getValid'),
    $btnSubmit = $validPower.find('.btn-validPower-submit');

  $btnGetValid.on('click', e => {
    e.preventDefault();

    mobile = $.trim($iptMobile.val());

    if (!mobile.length) {
      layer.msg('请输入手机号码')

      return
    }

    // !/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
    // if (!/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(mobile)) {
    if (!/^(0|86|17951)?1[0-9]{10}$/.test(mobile)) {
    layer.msg('手机号码格式错误');

      return
    }

    let loading = layer.load(2);

    $.ajax({
      url: base + getMobileCode,
      type: 'POST',
      data: {
        phone: mobile,
      }
    })
      .done(function (res) {
        console.log(res)

        if (res.code === 0) {
          isMobildValid = true
          layer.close(loading)
          layer.msg(`验证码发送成功`, {
            icon: 6
          })
          startTimer()
        } else {
          layer.msg(res.message || '验证码发送失败', {
            icon: 5
          })
        }
      })
      .fail(function (res) {
        console.log("error");
        layer.msg(res.message || '验证码发送失败', {
          icon: 5
        })
      })
      .always(function (res) {

      })
  })

  $btnSubmit.on('click', e => {
    e.preventDefault()

    let valid = $.trim($iptValid.val()),
      mobile = $.trim($iptMobile.val()),
      id = data.object.data.id;                   //用户的id号

    $.ajax({
      url: base + bindMobile,
      type: 'POST',
      data: {
        id: id,
        phone: mobile,
        identifyingCode: valid
      }
    })
      .done(function (res) {
        console.log(res)

        if (res.code === 0) {

          firstLogin(data);

        } else {
          layer.msg(res.message || '绑定手机号失败', {
            icon: 5
          })
        }

      })
      .fail(function (res) {
        console.log("error");
        layer.msg(res.message || '绑定手机号失败', {
          icon: 5
        })
      })
      .always(function (res) {

      })
  })

  $iptValid.on('change input', e => {
    valid = $.trim($iptValid.val())

    if (isMobildValid && valid.length) {
      $btnSubmit.removeAttr('disabled')
    } else {
      $btnSubmit.attr('disabled', true)
    }
  })

  $validPower.modal({backdrop: 'static', keyboard: false})

  function startTimer() {
    $btnGetValid.text(getValidIndex).attr('disabled', true)

    timer = setInterval(() => {
      if (getValidIndex - 1 > 0) {
        getValidIndex -= 1
        $btnGetValid.text(getValidIndex)
      } else {
        getValidIndex = getValidLimit
        $btnGetValid.text('发送验证码').removeAttr('disabled')
        clearInterval(timer)
        timer = null
      }
    }, 1000)
  }

}

function firstLogin(data) {

  if (data.object.status === 0) {
    layer.msg(`${ title }成功`, {
      icon: 6
    })

    // 重置表单
    $.extend(form.$data, form.$options.data())

    // 保存token数据
    Cookies.set('myToken', data.object.data.myToken, {
      // 保存的天数
      expires: 7,
      path: ''
    })

    // 判断是否是开发商登录
    if (data.object.data.enterpriseId !== null) {
      store.set('isDeveloper', true)
    }

    // 保存用户名
    store.set('loginName', data.object.data.loginName)
    // 保存用户类型
    store.set('loginType', data.object.data.type)
    // 保存权限
    // 有大量重复数据
    store.set('auth', _.uniq(data.object.data.menuCodes).join(','))

    // 设置菜单焦点为登录后首页面
    console.log('where menu from===>>', data)
    let menus = data.object.data.functions,
      menuToggle = Array(menus.length).fill('0')

    // console.log('menus===>>>', menus)

    menuToggle[0] = '1'

    const loginError = store.get('loginError')
    if (loginError) {
      console.log('loginError===>>', loginError)
    }
    try {
      // console.log('menus===>>', menus)
      // console.log('menuToggle===>>>', menuToggle)
      store.set('menuSelect', String(menus[0].children[0].id))
      store.set('menuToggle', menuToggle)
    } catch (e) {
      store.set('loginError', e)
    }

    // 保存菜单
    store.set('menus', menus);

    let jumpUrl = ''

    for (let i = 0, len = menus.length; i < len; i++) {
      if (jumpUrl) {
        break
      }

      if (!menus[i].children) {
        continue
      }

      for (let j = 0, jLen = menus[i].children.length; j < jLen; j++) {
        if (menus[i].children[j].clientUrl) {
          jumpUrl = menus[i].children[j].clientUrl
        }
      }
    }
    console.log('jumpUrl===>>', jumpUrl)
    // 跳转页面
    const host = location.origin
    // 跳转部分
    setTimeout(() => {

      console.log('跳转页面')
      // window.location = new URI(window.location.href).pathname(jumpUrl).query({})
      location.href = host + `/${jumpUrl}`
      form.isLock = false
    }, 1000)
  }

  if (data.object.status === 1) {

    layer.msg(`第一次登录，请先修改密码`, {
      icon: 6
    })

    // 重置表单
    $.extend(form.$data, form.$options.data())

    // 保存token数据
    Cookies.set('myToken', data.object.data.myToken, {
      // 保存的天数
      expires: 7,
      path: ''
    })
    // 保存用户名
    store.set('loginName', data.object.data.loginName)

    // 跳转页面
    setTimeout(() => {

      console.log('跳转页面')
      window.location.href = './accountManage/index.html'

      form.isLock = false
    }, 1000)
  }
}